import * as THREE from 'three'

import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
import{FBXLoader} from 'three/examples/jsm/loaders/FBXLoader'
import { CSS3DObject } from 'three/examples/jsm/renderers/css3drenderer';
import $ from 'jquery';
import { dataListStore } from '../../stores/dataList';
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min'
import {MTLLoader} from 'three/examples/jsm/loaders/MTLLoader';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
import { ElMessage } from 'element-plus'
const store = dataListStore();
let className = store.classNames;
// let data = store.dataList;
// let modellcNameList = store.modellcNameList;
const stateName = store.stateName; 

// const gui = new GUI();
export function loaderModel(data,scene,css3dLabelGroup,labelGroup,css3dLabelXQGroup,modelLcGroup,modelAGroup,modelBGroup,modelCGroup,modelDGroup) {
    let url = "static/shell_230618.glb";
    const loader = new GLTFLoader();
    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath( 'static/draco/' );
    loader.setDRACOLoader(dracoLoader);
    const hdrEquirect = new RGBELoader().setPath( 'static/hdr/' ).load( 'hdr_E.hdr', function (texture) {
			hdrEquirect.mapping = THREE.EquirectangularReflectionMapping;
			///scene.background = texture;
			scene.environment = texture;
        } );
    loader.load(url,(gltf) => {
        let gltfs = gltf.scene;
        gltfs.traverse(function (child) {
            let item = child.clone();
				if (item instanceof THREE.Mesh) {
                    item.name = item.name.replaceAll("_", '-');
                    item.material.metalness= 1.0;
				    item.material.roughness= 0.2;
                        if (data[item.name]) {
                        item.visible = false;
                        createLabel(item, data[item.name],item.name, css3dLabelGroup);
                        css3dLabelXQ(item, data[item.name], item.name, css3dLabelXQGroup);
                        labelGroup.add(item)
                        }  else if (item.name.indexOf('back-A') != -1 || item.name.indexOf('front-A') != -1 || item.name.indexOf('shell-A') != -1 || item.name.indexOf('under-A') != -1 ||
                            item.name == 'Box-A') {
                        modelAGroup.add(item)
                        } else if (item.name.indexOf('back-B') != -1 || item.name.indexOf('front-B') != -1 || item.name.indexOf('shell-B') != -1 || item.name.indexOf('under-B') != -1 ||
                            item.name == 'Box-B') {
                            modelBGroup.add(item)
                        } else if (item.name.indexOf('back-C') != -1 || item.name.indexOf('front-C') != -1 || item.name.indexOf('shell-C') != -1 || item.name.indexOf('under-C') != -1 ||
                            item.name == 'Box-C') {
                            modelCGroup.add(item)
                        } else if (item.name.indexOf('back-D') != -1 || item.name.indexOf('front-D') != -1 || item.name.indexOf('shell-D') != -1 || item.name.indexOf('under-D') != -1 ||
                            item.name == 'Box-D') {
                            modelDGroup.add(item)
                    }else if (item.name == 'hd-11' ||item.name == 'hd-12' ||item.name == 'hd-13' ||item.name == 'hd-14' ||item.name == 'hd-15' ||
                            item.name == 'hd-21' ||item.name == 'hd-22' ||item.name == 'hd-23' ||item.name == 'hd-24' ||item.name == 'hd-25' ||  
                            item.name == 'hd-31' ||item.name == 'hd-32' ||item.name == 'hd-33' ||item.name == 'hd-34' ||item.name == 'hd-35' ||
                            item.name == 'hd-41' ||item.name == 'hd-42' ||item.name == 'hd-43' ||item.name == 'hd-44' ||item.name == 'hd-45' ||
                            item.name == 'hd-51' ||item.name == 'hd-52' ||item.name == 'hd-53' ||item.name == 'hd-54' ||item.name == 'hd-55' ||
                            item.name == 'hd-61' ||item.name == 'hd-62' ||item.name == 'hd-63' ||item.name == 'hd-64' ||item.name == 'hd-65' ||
                            item.name == 'hd-71' ||item.name == 'hd-72' ||item.name == 'hd-73' ||item.name == 'hd-74' ||item.name == 'hd-75' ||
                            item.name == 'hd-81' ||item.name == 'hd-82' ||item.name == 'hd-83' ||item.name == 'hd-84' ||item.name == 'hd-85') {
                        // item.material = new THREE.MeshMatcapMaterial({
                        //     color: 0x6b6b6b,
                        // })	
                        item.userData.size = getSizeFn( item );
                        item.userData.position = {
                            x: item.position.x,
                            y: item.position.y,
                            z: item.position.z
                        };
                        item.userData.scale = {
                            x: item.scale.x,
                            y: item.scale.y,
                            z: item.scale.z
                        };

                        // item.material.userData.initH = item.position.y - 8.66525;
                        // item.material.clipIntersection = true;
                        //item.material.stencilWrite = true;
                        // item.material.stencilRef = 0;
                        // item.material.stencilFunc = THREE.NotEqualStencilFunc;
                        // item.material.stencilFail = THREE.ReplaceStencilOp;
                        // item.material.stencilZFail = THREE.ReplaceStencilOp;
                        // item.material.stencilZPass = THREE.ReplaceStencilOp;
                        // let plan = new THREE.Plane( new THREE.Vector3( 0, -1, 0 ), item.material.userData.initH );
                        // item.material.clippingPlanes = [plan];
         //                item.onAfterRender = function ( renderer ) {

         //                    renderer.clearStencil();

         //                };

					    // item.renderOrder =  1.1;

                        // var helpers = new THREE.Group();
                        // helpers.add( new THREE.PlaneHelper( plan, 800, 0xDC143C ) );
                        // scene.add(helpers)

                        modelLcGroup.add(item);
						
						// let itemTop = child.clone();
						// itemTop.material = child.material.clone();
						// itemTop.name = item.name+'-top';
						// modelLcGroup.add(itemTop);
						
                    } else {
                        scene.add(item)
                    }
                } 
            }
        );
    })
}

export function loaderGlbModel(data,scene,css3dLabelGroup,labelGroup,css3dLabelXQGroup,modelLcGroup) {
    let url = "static/AAA.glb"
    const loader = new GLTFLoader();
    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath( 'static/draco/' );
    loader.setDRACOLoader( dracoLoader );
	const hdrEquirect = new RGBELoader().setPath( 'static/hdr/' ).load( 'hdr_E.hdr', function (texture) {
	        hdrEquirect.mapping = THREE.EquirectangularReflectionMapping;
			///scene.background = texture;
			scene.environment = texture;
	    } );
    loader.load(url, (gltf) => {
        let gltfs = gltf.scene;
        gltfs.traverse(function (child) {
            let item = child.clone();
            if (item instanceof THREE.Mesh) { 
				console.log(item.material);
                //console.log(item.position,item.name);
				 item.material.metalness= 1.0;
				 item.material.roughness= 0.2;
				 // item.material.exposure = 1;
				 // item.material.specularColor = 1;
				 // item.material.emissiveIntensity= 0;
				// item.material.normalMap = item.userData.normalMap
				//item.material.color = new THREE.Color(0xffffff);
				//item.material = 
                scene.add(item)
            }
            
            
        })
    })
}


export function fbxLoaderModel(data,scene,css3dLabelGroup,labelGroup,css3dLabelXQGroup,modelLcGroup,modelAGroup,modelBGroup,modelCGroup,modelDGroup) {
    let url = "static/A692_F.FBX"
    const loader = new FBXLoader();
    loader.load(url, (fbx) => {
        fbx.traverse(function (child) {
            let item = child.clone();
            if (item instanceof THREE.Mesh) {
                item.name = item.name.replaceAll("_", '-');
                  console.log(item.name);
                 if (data[item.name]) {
                    item.visible = false;
                    createLabel(item, data[item.name],item.name, css3dLabelGroup);
                    css3dLabelXQ(item, data[item.name], item.name, css3dLabelXQGroup);
                    labelGroup.add(item)
                 }  else if (item.name == 'yy-1' || item.name == 'yy-2' || item.name == 'yy-3'
                    || item.name == 'lianjie-1' || item.name == 'lianjie-2' ||
                    item.name == 'czs-1' || item.name == 'czs-2' || item.name == 'czs-3') {
                    let map = item.material.map;
                    let material = new THREE.MeshMatcapMaterial({
                        map: map
                    })
                    item.material = material;
                    scene.add(item)
                 } else if (item.name.indexOf('A-Back') != -1 || item.name.indexOf('A-Front') != -1 || item.name.indexOf('shell-A') != -1 || item.name.indexOf('Under-A') != -1 ||
                        item.name == 'hd-11-1' ||item.name == 'hd-12-1' ||item.name == 'hd-13-1' ||item.name == 'hd-14-1' ||item.name == 'hd-15-1' ||
                        item.name == 'hd-21-1' ||item.name == 'hd-22-1' ||item.name == 'hd-23-1' ||item.name == 'hd-24-1' ||item.name == 'hd-25-1'
                 ) {
                     if (item.name.indexOf('shell-A') != -1) {
                         item.material = material.clone();
                         let edges = new THREE.EdgesGeometry(item.geometry);
                         let linemodel = new THREE.LineSegments(edges, LineBasicMaterial.clone())
                         linemodel.name = item.name + "-Line";
                        linemodel.position.copy(item.position);
                        let axis = new THREE.Vector3(1,0,0);
                        linemodel.rotateOnAxis(axis, -Math.PI / 2);
                        modelAGroup.add(linemodel)
                     } else if (item.name.indexOf('hd') != -1) {
                         if (item.material.length > 1) {
                             let map1 = item.material[0].map;
                             let map2 = item.material[1].map;
                             item.material[0] = new THREE.MeshLambertMaterial({
                                 map: map1,
                                 transparent:false
                             })
                             item.material[1] = new THREE.MeshLambertMaterial({
                                 map: map2,
                                 transparent:false
                             })
                         }
                        let edges = new THREE.EdgesGeometry(item.geometry);
                         let linemodel = new THREE.LineSegments(edges, LineBasicMaterial.clone())
                         linemodel.name = item.name + "-Line";
                        linemodel.position.copy(item.position);
                        let axis = new THREE.Vector3(1,0,0);
                        linemodel.rotateOnAxis(axis, -Math.PI / 2);
                        modelAGroup.add(linemodel)
                    }
                    //  let map = item.material.map;
                    // let material = new THREE.MeshLambertMaterial({
                    //     map:map
                    // })
                    // item.material = material;
                    modelAGroup.add(item)
                 } else if (item.name.indexOf('B-Back') != -1 || item.name.indexOf('B-Front') != -1 || item.name.indexOf('shell-B') != -1 || item.name.indexOf('Under-B') != -1 ||
                     item.name == 'hd-31-1' ||item.name == 'hd-32-1' ||item.name == 'hd-33-1' ||item.name == 'hd-34-1' ||item.name == 'hd-35-1' ||
                       item.name == 'hd-41-1' ||item.name == 'hd-42-1' ||item.name == 'hd-43-1' ||item.name == 'hd-44-1' ||item.name == 'hd-45-1' 
                 ) {
                     if (item.name.indexOf('shell-B') != -1) {
                         item.material = material.clone();
                         let edges = new THREE.EdgesGeometry(item.geometry);
                        let linemodel = new THREE.LineSegments(edges,LineBasicMaterial.clone())
                        linemodel.name = item.name + "-Line";
                        linemodel.position.copy(item.position);
                        let axis = new THREE.Vector3(1,0,0);
                        linemodel.rotateOnAxis(axis, -Math.PI / 2);
                        modelBGroup.add(linemodel)
                    }else if (item.name.indexOf('hd') != -1) {
                         if (item.material.length > 1) {
                             let map1 = item.material[0].map;
                             let map2 = item.material[1].map;
                             item.material[0] = new THREE.MeshLambertMaterial({
                                 map: map1,
                                 transparent:false
                             })
                             item.material[1] = new THREE.MeshLambertMaterial({
                                 map: map2,
                                 transparent:false
                             })
                         }
                        let edges = new THREE.EdgesGeometry(item.geometry);
                         let linemodel = new THREE.LineSegments(edges, LineBasicMaterial.clone())
                         linemodel.name = item.name + "-Line";
                        linemodel.position.copy(item.position);
                        let axis = new THREE.Vector3(1,0,0);
                        linemodel.rotateOnAxis(axis, -Math.PI / 2);
                        modelBGroup.add(linemodel)
                    }
                     modelBGroup.add(item)
                 } else if (item.name.indexOf('C-Back') != -1 || item.name.indexOf('C-Front') != -1 || item.name.indexOf('shell-C') != -1 || item.name.indexOf('Under-C') != -1 ||
                     item.name == 'hd-51-1' ||item.name == 'hd-52-1' ||item.name == 'hd-53-1' ||item.name == 'hd-54-1' ||item.name == 'hd-55-1' ||
                     item.name == 'hd-61-1' || item.name == 'hd-62-1' || item.name == 'hd-63-1' || item.name == 'hd-64-1' || item.name == 'hd-65-1' 
                 ) {
                     if (item.name.indexOf('shell-C') != -1) {
                         item.material = material.clone();
                         let edges = new THREE.EdgesGeometry(item.geometry);
                         let linemodel = new THREE.LineSegments(edges, LineBasicMaterial.clone())
                         linemodel.name = item.name + "-Line";
                        linemodel.position.copy(item.position);
                        let axis = new THREE.Vector3(1,0,0);
                        linemodel.rotateOnAxis(axis, -Math.PI / 2);
                        modelCGroup.add(linemodel)
                    }else if (item.name.indexOf('hd') != -1) {
                         if (item.material.length > 1) {
                             let map1 = item.material[0].map;
                             let map2 = item.material[1].map;
                             item.material[0] = new THREE.MeshLambertMaterial({
                                 map: map1,
                                 transparent:false
                             })
                             item.material[1] = new THREE.MeshLambertMaterial({
                                 map: map2,
                                 transparent:false
                             })
                         }
                        let edges = new THREE.EdgesGeometry(item.geometry);
                         let linemodel = new THREE.LineSegments(edges, LineBasicMaterial.clone())
                         linemodel.name = item.name + "-Line";
                        linemodel.position.copy(item.position);
                        let axis = new THREE.Vector3(1,0,0);
                        linemodel.rotateOnAxis(axis, -Math.PI / 2);
                        modelCGroup.add(linemodel)
                    }
                     modelCGroup.add(item)
                 } else if (item.name.indexOf('D-Back') != -1 || item.name.indexOf('D-Front') != -1 || item.name.indexOf('shell-D') != -1 || item.name.indexOf('Under-D') != -1 ||
                     item.name == 'hd-71-1' ||item.name == 'hd-72-1' ||item.name == 'hd-73-1' ||item.name == 'hd-74-1' ||item.name == 'hd-75-1' ||
                     item.name == 'hd-81-1' ||item.name == 'hd-82-1' ||item.name == 'hd-83-1' ||item.name == 'hd-84-1' ||item.name == 'hd-85-1'
                 ) {
                     if (item.name.indexOf('shell-D') != -1) {
                         item.material = material.clone();
                         let edges = new THREE.EdgesGeometry(item.geometry);
                         let linemodel = new THREE.LineSegments(edges, LineBasicMaterial.clone())
                         linemodel.name = item.name + "-Line";
                        linemodel.position.copy(item.position);
                        let axis = new THREE.Vector3(1,0,0);
                        linemodel.rotateOnAxis(axis, -Math.PI / 2);
                        modelDGroup.add(linemodel)
                     }else if (item.name.indexOf('hd') != -1) {
                         if (item.material.length > 1) {
                             let map1 = item.material[0].map;
                             let map2 = item.material[1].map;
                             item.material[0] = new THREE.MeshLambertMaterial({
                                 map: map1,
                                 transparent:false
                             })
                             item.material[1] = new THREE.MeshLambertMaterial({
                                 map: map2,
                                 transparent:false
                             })
                         }
                        let edges = new THREE.EdgesGeometry(item.geometry);
                         let linemodel = new THREE.LineSegments(edges, LineBasicMaterial.clone())
                         linemodel.name = item.name + "-Line";
                        linemodel.position.copy(item.position);
                        let axis = new THREE.Vector3(1,0,0);
                        linemodel.rotateOnAxis(axis, -Math.PI / 2);
                        modelDGroup.add(linemodel)
                    }
                     modelDGroup.add(item)
                }else if (item.name == 'hd-11' ||item.name == 'hd-12' ||item.name == 'hd-13' ||item.name == 'hd-14' ||item.name == 'hd-15' ||
                        item.name == 'hd-21' ||item.name == 'hd-22' ||item.name == 'hd-23' ||item.name == 'hd-24' ||item.name == 'hd-25' ||  
                        item.name == 'hd-31' ||item.name == 'hd-32' ||item.name == 'hd-33' ||item.name == 'hd-34' ||item.name == 'hd-35' ||
                        item.name == 'hd-41' ||item.name == 'hd-42' ||item.name == 'hd-43' ||item.name == 'hd-44' ||item.name == 'hd-45' ||
                        item.name == 'hd-51' ||item.name == 'hd-52' ||item.name == 'hd-53' ||item.name == 'hd-54' ||item.name == 'hd-55' ||
                        item.name == 'hd-61' ||item.name == 'hd-62' ||item.name == 'hd-63' ||item.name == 'hd-64' ||item.name == 'hd-65' ||
                        item.name == 'hd-71' ||item.name == 'hd-72' ||item.name == 'hd-73' ||item.name == 'hd-74' ||item.name == 'hd-75' ||
                        item.name == 'hd-81' ||item.name == 'hd-82' ||item.name == 'hd-83' ||item.name == 'hd-84' ||item.name == 'hd-85') {
                    // item.material = new THREE.MeshMatcapMaterial({
                    //     color: 0x6b6b6b,
                    // })
                     console.log(item);
                    item.userData.size = getSizeFn( item );
                    item.userData.position = {
                        x: item.position.x,
                        y: item.position.y,
                        z: item.position.z
                     };
                     item.userData.scale = {
                        x: item.scale.x,
                        y: item.scale.y,
                        z: item.scale.z
                     };
                    item.material.userData.initH = item.position.y - 3.8610129;
                    item.material.clipIntersection = true;
                    let plan = new THREE.Plane( new THREE.Vector3( 0, -1, 0 ), item.material.userData.initH );
                    item.material.clippingPlanes = [ plan ];

                    var helpers = new THREE.Group();
				    helpers.add( new THREE.PlaneHelper( plan, 40, 0xDC143C ) );
                    scene.add(helpers)

                    modelLcGroup.add(item);
                } else {
                    scene.add(item)
                }
            } 
        })
    })
}



// 计算缩放比例
function getSizeFn( mesh ){
    let box = new THREE.Box3();
    box.setFromObject( mesh );
    let size = new THREE.Vector3();
    box.getSize(size);
   // console.log( "Width: " + size.x + ", Height: " + size.y + ", Depth: " + size.z );
    return{
        width: Number( size.x ).toFixed(2),
        height: Number( size.y ).toFixed(2),
        depth: Number( size.z ).toFixed(2)
    }
    
}

function createLabel(item, datas,label, css3dLabelGroup) {
   // console.log(datas,label);
    let data = JSON.stringify(datas);
    let html = `<div class="labelTitles ${className[datas.state]} ${label} " onclick='showLabel(${data},"${label}")'>
        <span>${label}</span>
    </div>`;
    let css3dLabel = new CSS3DObject($(html)[0]);
    css3dLabel.position.x = item.position.x;
    css3dLabel.position.y = item.position.y;
    css3dLabel.position.z = item.position.z;
    css3dLabel.name = label;
    css3dLabel.scale.set(0.35, 0.35, 0.35);
    css3dLabel.rotateY( Math.PI );
    css3dLabelGroup.add(css3dLabel);
}

function css3dLabelXQ(item, datas,label, css3dLabelXQGroup) {
    let data = JSON.stringify(datas);
    let wz = "";
    if (datas.hopper.indexOf('A1-') != -1 || datas.hopper.indexOf('A2-') != -1) {
        wz = '除尘器A侧右室'
    } else if (datas.hopper.indexOf('A3-') != -1 || datas.hopper.indexOf('A4-') != -1) {
        wz = '除尘器A侧左室'
    }else if (datas.hopper.indexOf('B1-') != -1 || datas.hopper.indexOf('B2-') != -1) {
        wz = '除尘器B侧右室'
    }else if (datas.hopper.indexOf('B3-') != -1 || datas.hopper.indexOf('B4-') != -1) {
        wz = '除尘器B侧左室'
    }
    let html = `<div class="labelXq">
            <div class="top ${className[datas.state]} ${label}">
                <div class="title"><span>${wz}</span>
                    <div class="closeIcon" onClick='closeLabel(${data},"${label}")'></div>
                </div>
                <div class="center">
                    <div class="name centerCenter">
                        <span class="labelTitle">灰斗名称：</span>
                        <span class="labelNr labelNrMc">${label}</span>
                    </div>
                    <div class="hw centerCenter">
                        <span class="labelTitle">灰位：</span>
                        <span class="labelNr labelNrHw ${className[datas.state]}">${datas.height.toFixed(2)}米</span>
                    </div>
                    <div class="bjzt centerCenter">
                        <span class="labelTitle">报警状态：</span>
                        <span class="labelNr labelNrZt ${className[datas.state]}">${stateName[datas.state]}</span>
                    </div>
                    <div class="bjzt centerCenter flex-press-more">
                        <div class="labelTitle">灰荷载：</div>
                        <div class="labelNr labelNrHzai ${className[datas.state]}">
                            <div class="in-press"></div>
                        </div>
                        <span class="${className[datas.state]}">${(datas.load_rate.toFixed(4) * 100).toFixed(2)} %</span>
                    </div>
                    <div class="bc">灰斗输灰不畅</div>
                </div>
            </div>
            <div class="bottom ${className[datas.state]} ${label}">

            </div>
    </div>`;
    let css3dLabel = new CSS3DObject($(html)[0]);
    css3dLabel.position.x = item.position.x ;
    css3dLabel.position.y = item.position.y + 50;
    css3dLabel.position.z = item.position.z;
    css3dLabel.name = label;
    css3dLabel.scale.set(0.5, 0.5, 0.5);
    css3dLabel.rotateY(Math.PI);
    css3dLabel.visible = false;
    if (datas.state == 1 ||datas.state == 2 || datas.state == 3|| datas.state == 4|| datas.state == 5) {
        css3dLabel.visible = true;
    }
    css3dLabelXQGroup.add(css3dLabel);
}

function createSpotShadowMesh() {
	const canvas = document.createElement( 'canvas' );
	canvas.width = 128;
	canvas.height = 128;

	const context = canvas.getContext( '2d' );
	const gradient = context.createRadialGradient( canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2 );
	gradient.addColorStop( 0.1, 'rgba(130,130,130,1)' );
	gradient.addColorStop( 1, 'rgba(255,255,255,1)' );

	context.fillStyle = gradient;
	context.fillRect( 0, 0, canvas.width, canvas.height );

	const shadowTexture = new THREE.CanvasTexture( canvas );

	const geometry = new THREE.PlaneGeometry();
	const material = new THREE.MeshBasicMaterial( {
		map: shadowTexture, blending: THREE.MultiplyBlending, toneMapped: false
	} );

	const mesh = new THREE.Mesh( geometry, material );
	mesh.rotation.x = - Math.PI / 2;

	return mesh;

}
